package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.system.dtos.request.agent.AddAgentInfoReq;
import com.rightsidetech.system.dtos.request.agent.AgentInfoReq;
import com.rightsidetech.system.dtos.request.agent.AreaAgentListReq;
import com.rightsidetech.system.dtos.request.agent.UpdateAgentInfoReq;
import com.rightsidetech.system.dtos.request.store.ActAreaAgentStoreReq;
import com.rightsidetech.system.dtos.response.agent.AgentInfoResp;
import com.rightsidetech.system.dtos.response.agent.AgentListResp;
import com.rightsidetech.system.dtos.response.agent.AgentSearchResp;
import com.rightsidetech.system.dtos.response.agent.AreaAgentListResp;
import com.rightsidetech.system.dtos.response.store.ActAgentResp;
import com.rightsidetech.system.dtos.response.store.ActAreaAgentStoreResp;
import com.rightsidetech.system.entity.SysAgentInfo;
import com.rightsidetech.system.entity.SysAgentLoginHistory;
import com.rightsidetech.system.entity.SysAgentLoginInfo;
import com.rightsidetech.system.mapper.*;
import com.rightsidetech.system.service.AgentInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Package: com.rightsidetech.system.service.impl
 * @ClassName: AgentInfoServiceImpl
 * @Author: yinj
 * @CreateTime: 2021/10/26 11:36
 */
@Service("agentInfoServiceImpl")
public class AgentInfoServiceImpl implements AgentInfoService {

    @Resource
    private SysAgentInfoMapper sysAgentInfoMapper;
    @Resource
    private SysAgentLoginInfoMapper sysAgentLoginInfoMapper;
    @Resource
    private SysAgentLoginHistoryMapper sysAgentLoginHistoryMapper;
    @Resource
    private SysCompanyAreaMapper sysCompanyAreaMapper;
    @Resource
    private SysStoreInfoMapper sysStoreInfoMapper;


    @Override
    public ResponseData<PageInfo<AgentInfoResp>> page(AgentInfoReq request) {
        PageHelper.startPage(request.getPageNo(),request.getPageSize());
        List<AgentInfoResp> list = sysAgentInfoMapper.page(request);
        return ResponseData.success(new PageInfo<>(list));
    }

    @Override
    public ResponseData add(AddAgentInfoReq req, Long loginInfoId) {
        //判断重复
        SysAgentInfo sysAgentInfo = sysAgentInfoMapper.selectByPhoneNo(req.getMobileNo());
        if (!ObjectUtils.isEmpty(sysAgentInfo)){
            return ResponseData.fail(CodeIdEnum.REPEATPHONE);
        }
        sysAgentInfo = sysAgentInfoMapper.selectByName(req.getName());
        if (!ObjectUtils.isEmpty(sysAgentInfo)){
            return ResponseData.fail("代理商名称已存在");
        }

        SysAgentInfo agentInfo = new SysAgentInfo();
        agentInfo.setName(req.getName());
        agentInfo.setPrincipalName(req.getPrincipalName());
        agentInfo.setMobileNo(req.getMobileNo());
        agentInfo.setAreaId(req.getAreaId());
        agentInfo.setCustomerMobileNo(req.getCustomerMobileNo());
        agentInfo.setCreaterId(loginInfoId);
        agentInfo.setCreatedAt(new Date());
        sysAgentInfoMapper.insertSelective(agentInfo);

        return ResponseData.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData update(UpdateAgentInfoReq req, Long loginInfoId) {
        SysAgentInfo sysAgentInfo2 = sysAgentInfoMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(sysAgentInfo2)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        //判断重复
        SysAgentInfo sysAgentInfo = sysAgentInfoMapper.selectByPhoneNo(req.getMobileNo());
        if (!ObjectUtils.isEmpty(sysAgentInfo) && !sysAgentInfo.getId().equals(req.getId())){
            return ResponseData.fail(CodeIdEnum.REPEATPHONE);
        }
        sysAgentInfo = sysAgentInfoMapper.selectByName(req.getName());
        if (!ObjectUtils.isEmpty(sysAgentInfo) && !sysAgentInfo.getId().equals(req.getId())){
            return ResponseData.fail("代理商名称已存在");
        }
        SysAgentInfo agentInfo = new SysAgentInfo();
        agentInfo.setId(req.getId());
        agentInfo.setName(req.getName());
        agentInfo.setPrincipalName(req.getPrincipalName());
        agentInfo.setMobileNo(req.getMobileNo());
        agentInfo.setAreaId(req.getAreaId());
        agentInfo.setCustomerMobileNo(req.getCustomerMobileNo());
        agentInfo.setUpdaterId(loginInfoId);
        agentInfo.setUpdatedAt(new Date());
        sysAgentInfoMapper.updateByPrimaryKeySelective(agentInfo);

        //判断大区是否被修改
        if(!StringUtils.isEmpty(req.getAreaId()) && !StringUtils.isEmpty(sysAgentInfo2.getAreaId()) && !Objects.equals(sysAgentInfo2.getAreaId(), req.getAreaId())){
            //修改该代理商下门店的大区id
            sysStoreInfoMapper.updateAreaIdByAgentId(req.getAreaId(),req.getId());
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData open(Long id, Byte status,Long loginInfoId) {
        SysAgentInfo sysAgentInfo = sysAgentInfoMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sysAgentInfo)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        if (status == 1 && sysAgentInfo.getStatus() == 1){
            return ResponseData.fail("开启状态,无需开启");
        }
        if (status == -1 && sysAgentInfo.getStatus() == -1){
            return ResponseData.fail("关闭状态,无需关闭");
        }
        SysAgentInfo agentInfo = new SysAgentInfo();
        agentInfo.setId(id);
        agentInfo.setStatus(status);
        agentInfo.setUpdaterId(loginInfoId);
        agentInfo.setUpdatedAt(new Date());
        sysAgentInfoMapper.updateByPrimaryKeySelective(agentInfo);

        //关闭 账号 退出登录
        List<SysAgentLoginInfo> loginInfoList = sysAgentLoginInfoMapper.findByAgentInfoId(id);
        if (!CollectionUtils.isEmpty(loginInfoList)){
            //全部退出登录
            for (SysAgentLoginInfo loginInfo : loginInfoList){
                SysAgentLoginHistory historyData = sysAgentLoginHistoryMapper.selectMaxIdByLoginInfoId(loginInfo.getId());
                if (!ObjectUtils.isEmpty(historyData)){
                    historyData.setLogoutTime(new Date());
                    historyData.setEffectiveTime(historyData.getLogoutTime());
                    historyData.setToken(null);
                    sysAgentLoginHistoryMapper.updateBatch(historyData);
                }

            }
        }

        return ResponseData.success();
    }

    @Override
    public ResponseData del(Long id, Long loginInfoId) {
        SysAgentInfo sysAgentInfo = sysAgentInfoMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(sysAgentInfo)){
            return ResponseData.fail(CodeIdEnum.EMPTY_DATA);
        }
        //判断是否绑定账号
        List<SysAgentLoginInfo> byAgentInfoId = sysAgentLoginInfoMapper.findByAgentInfoId(id);
        if (!CollectionUtils.isEmpty(byAgentInfoId)){
            return ResponseData.fail("已绑定账号,请删除账号后操作");
        }
        Long s = sysAgentInfo.getId();
        if(sysStoreInfoMapper.findStoreNumByAgentId(sysAgentInfo.getId())>0){
            return ResponseData.fail("该代理商下拥有门店，无法删除");
        }
        SysAgentInfo agentInfo = new SysAgentInfo();
        agentInfo.setId(id);
        agentInfo.setIsDeleted((byte)1);
        agentInfo.setUpdaterId(loginInfoId);
        agentInfo.setUpdatedAt(new Date());
        sysAgentInfoMapper.updateByPrimaryKeySelective(agentInfo);
        return ResponseData.success();
    }

    @Override
    public ResponseData<List<AgentSearchResp>> search(String content,Long areaId) {
        List<AgentSearchResp> list = sysAgentInfoMapper.search(content,null,areaId);
        return ResponseData.success(list);
    }

    @Override
    public List<AgentInfoResp> exportAgentList(AgentInfoReq req) {
        return  sysAgentInfoMapper.page(req);
    }

    @Override
    public List<Long> selectAllAgentId() {
        return sysAgentInfoMapper.selectAgentIdAll();
    }

    @Override
    public ResponseData<List<AgentSearchResp>> searchOpen(String content,Long areaId) {
        List<AgentSearchResp> list = sysAgentInfoMapper.search(content,(byte)1,areaId);
        return ResponseData.success(list);
    }


    @Override
    public List<AgentListResp> findAgentByAreaOrAgentId(AreaAgentListReq request) {
        return sysAgentInfoMapper.findAgentByAreaOrAgentId(request);
    }

    @Override
    public List<AreaAgentListResp> findAreaByAreaOrAgentId(AreaAgentListReq request) {
        return sysCompanyAreaMapper.findAreaByAreaOrAgentId(request);
    }

    @Override
    public AgentInfoResp selectById(Long id) {
        return sysAgentInfoMapper.selectById(id);
    }


    @Override
    public List<ActAgentResp> selectAgentList(ActAreaAgentStoreReq req) {
        return sysAgentInfoMapper.selectActAgentList(req);
    }

    @Override
    public List<ActAreaAgentStoreResp> selectAreaList(ActAreaAgentStoreReq req) {
        return sysCompanyAreaMapper.selectActAreaList(req);
    }
}
